package com.blog.filter;

import com.alibaba.fastjson.JSON;
import com.blog.domain.ResponseResult;
import com.blog.domain.entity.LoginUser;
import com.blog.enums.AppHttpCodeEnum;
import com.blog.utils.JwtUtil;
import com.blog.utils.RedisCache;
import com.blog.utils.WebUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

	@Autowired
	private RedisCache redisCache;
	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
		//获取请求头中的token
		String token = request.getHeader("token");
		//放行
		if (!StringUtils.hasText(token)){
			//没有token，说明该接口不需要登录，直接放行
			filterChain.doFilter(request,response);
			return;
		}
		//解析获取userid
		Claims claims = null;
		try {
			claims = JwtUtil.parseJWT(token);
		} catch (Exception e) {
			e.printStackTrace();
			//throw new RuntimeException(e);
			//token超时、非法。需要响应给前端重新登陆
			ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
			WebUtils.renderString(response, JSON.toJSONString(result));
			return;
		}
		String userid = claims.getSubject();
		//从redis中获取用户信息
		LoginUser loginUser = redisCache.getCacheObject("login" + userid);
		if(Objects.isNull(loginUser)){
			//说明登录过期  提示重新登录
			ResponseResult result =
					ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
			WebUtils.renderString(response, JSON.toJSONString(result));
			return;
		}
		//将用户信息存入SecurityContextHolder
		UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser,null,null);

		SecurityContextHolder.getContext().setAuthentication(authenticationToken);

		filterChain.doFilter(request,response);

	}
}
